package com.sinosoft.lk.lkssosampleserver.controller;

import com.sinosoft.lk.core.server.SsoServerHelper;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 绫小路
 * @date 2021/3/14 19:29
 * @description
 */
@Controller
public class SsoAccessController {

  @Autowired
  private SsoServerHelper ssoServerHelper;

  @Autowired
  private HttpServletRequest request;

  @GetMapping("sso_login")
  public String ssoLogin() {
    String service = request.getParameter("service");
    request.setAttribute("service", service);
    return "ssoLogin";
  }

  @PostMapping("ssoLogin")
  @ResponseBody
  public Object ssoLogin(HttpServletRequest request) {
    Map<String, Object> result = new HashMap<>();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    if ("123".equals(username) && "123".equals(password)) {
      Map<String, String> user = new HashMap<>();
      user.put("username", "123");
      user.put("nickname", "张三");
      user.put("sex", "男");
      String token = "sso-server-001" + UUID.randomUUID().toString();
      //sso login
      ssoServerHelper.loginStr(token, user, 60 * 60 * 8);
      result.put("code", 0);
      result.put("msg", "登录成功！");
      result.put("data", token);
      return result;
    }
    result.put("code", 1);
    result.put("msg", "账号或密码错误！");
    return result;
  }

  @GetMapping("sso_logout")
  @ResponseBody
  public Object ssoLogout(HttpServletRequest request) {
    String token = request.getParameter("token");
    Map<String, String> loginUserInfo = ssoServerHelper.getLoginUserInfo(token);
    System.out.println("有人注销：" + loginUserInfo);
    ssoServerHelper.logout(token);
    return "注销成功！" + loginUserInfo;
  }

  @PostMapping("sso_logout")
  @ResponseBody
  public Object ssoLogoutPost(HttpServletRequest request) {
    return this.ssoLogout(request);
  }
}
